package net.jxvtc.eshop.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import net.jxvtc.eshop.domain.Order;
import net.jxvtc.eshop.domain.OrderItem;
import net.jxvtc.eshop.domain.Product;
import net.jxvtc.eshop.utils.DataSourceUtils;

public class ProductDao {

	public Product findProductById(String id) throws SQLException{
		String sql = "select * from products where id=?";
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		return runner.query(sql, new BeanHandler<Product>(Product.class), id);
	}

	public void changeProductNum(Order order) throws SQLException{
		String sql = "update products set pnum=pnum-? where id=?";
		QueryRunner runner = new QueryRunner();
		List<OrderItem> items = order.getOrderItems();
		Object[][] params = new Object[items.size()][2];

		for (int i = 0; i < params.length; i++) {
			params[i][0] = items.get(i).getBuynum();
			params[i][1] = items.get(i).getP().getId();
		}

		runner.batch(DataSourceUtils.getConnection(), sql, params);
		
	}

	public int findAllCount(String category) throws SQLException{
		String sql = "select count(*) from products";

		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

		if (!"全部商品".equals(category)) {
			sql += " where category=?";

			Long count = (Long) runner
					.query(sql, new ScalarHandler(), category);
			return count.intValue();
		} else {
			Long count = (Long) runner.query(sql, new ScalarHandler());

			return count.intValue();
		}
	}

	public List<Product> findByPage(int currentPage, int currentCount, String category) throws SQLException{
		// 要执行的sql语句
				String sql = null;
				// 参数
				Object[] obj = null;
				// 如果category不为null,代表是按分类查找
				if (!"全部商品".equals(category)) {
					sql = "select * from products  where category=? limit ?,?";
					obj = new Object[] { category, (currentPage - 1) * currentCount,
							currentCount, };
				} else {
					sql = "select * from products  limit ?,?";
					obj = new Object[] { (currentPage - 1) * currentCount,
							currentCount, };
				}
				QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
				return runner.query(sql, new BeanListHandler<Product>(Product.class),
						obj);
	}

}
